package q934_shortestBridge;

import java.util.LinkedList;
import java.util.Queue;

/*
需要找出两座岛屿之间的最短距离
 */
public class Solution {
    int shortest = Integer.MAX_VALUE;
    int[][] dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
    
    public int shortestBridge(int[][] grid) {
        // 首先使用一个方法 当我们找到第一个岛屿时，利用dfs将其所有点改为2
        // 用来区分两个岛屿
        changeOneLand(grid);

        // 然后当我们每次遇到2时，就开示bfs找该点到另一个岛屿的最短距离
        for (int i = 0; i < grid.length; ++i) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 2) bfs(grid, i, j);
            }
        }

        return shortest;
    }
    // 更改第一个岛屿的方法
    private void changeOneLand(int[][] grid) {
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    dfs(grid, i, j);
                    return;
                }
            }
        }
    }
    // 利用bfs找出第一个岛屿某处到第二个岛屿的最短距离
    private void bfs(int[][] grid, int r, int c) {
        // 注意每次都需一个新的vis数组 用来记录已经走过的节点
        boolean[][] vis = new boolean[grid.length][grid[0].length];

        Queue<int[]> queue = new LinkedList<>();
        vis[r][c] = true;
        queue.offer(new int[]{r, c});
        int steps = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int[] land = queue.poll();
                for (int[] dir : dirs) {
                    int newR = land[0] + dir[0], newC = land[1] + dir[1];
                    if (newR >= 0 && newC >= 0 && newR < grid.length && newC < grid[0].length && grid[newR][newC] != 2) {
                        if (grid[newR][newC] == 1) {
                            shortest = Math.min(steps, shortest);
                            return;
                        }
                        if (grid[newR][newC] == 0 && !vis[newR][newC]) {
                            queue.offer(new int[]{newR, newC});
                            vis[newR][newC] = true;
                        }
                    }
                }
            }
            ++steps;
        }
    }
    // 更改岛屿1的所有点的值为2
    private void dfs(int[][] grid, int i, int j) {
        if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] == 2 || grid[i][j] == 0) return;
        grid[i][j] = 2;

        dfs(grid, i + 1, j);
        dfs(grid, i, j + 1);
        dfs(grid, i - 1, j);
        dfs(grid, i, j - 1);
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        int[][] a = {{0, 1}, {1, 0}};
        System.out.println(s.shortestBridge(a));
    }
}
